#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "protocol.h"

#define BUFFSIZE 1024

int serverConnect(char *MYIP, char *MYPORT)
{
    int sockfd;
    struct sockaddr_in myaddr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket()");
        exit(1);
    }
    
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(atoi(MYPORT));
    inet_pton(AF_INET, MYIP, &myaddr.sin_addr);
    if (bind(sockfd, (void *)&myaddr, sizeof(myaddr)) < 0)
    {
        perror("bind()");
        exit(1);
    }
    return sockfd;
}

int main(int argc, char **argv)
{
    if (argc < 3)
    {   
        fprintf(stderr, "Usage:\n");
        exit(1);
    }

    int sockid, size;
    struct msg_st *recvbuff;
    int ret;
    
    sockid = serverConnect(argv[1], argv[2]);
	size = sizeof(struct msg_st) + NAMESIZE - 1;
	recvbuff = malloc(size);
	if (recvbuff == NULL)
	{
		perror("malloc()");
		exit(1);
	}
 
	
    while (1)
    {

        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        char ipstr[BUFFSIZE] = {0};

        ret = recvfrom(sockid, recvbuff, size, 0, (void *)&client, &len);  
        if (ret > 0)
        {
            printf("Data from (%s : %d)\n", inet_ntop(AF_INET, &client.sin_addr, ipstr, BUFFSIZE), client.sin_port);
            puts(recvbuff->name);
            printf("math : %d\n", ntohl(recvbuff->math));
            printf("English : %d\n", ntohl(recvbuff->math));
        }

        sendto(sockid, "Ok!\n", 5, 0, (void *)&client, len);
    }
    close(sockid);
}
